package com.test.service;

import com.test.current.CustomizeAqsLock;
import com.test.mapper.SaleTicketMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.CustomAutowireConfigurer;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;

@Service
@Slf4j
public class SaleTicketservcie {

    @Autowired
    SaleTicketMapper saleTicketMapper;


    static CustomizeAqsLock sysnc = new CustomizeAqsLock();

    /**
     * 由于stock未加锁，导致超卖
     * 解决方案    synchronized () 基于底层c++语言实现的同步机制  1.6之后性能优化，与aqs性能差不多
     * lock-> ReentrantLock 用到leAbstractQueuedSynchronizer aqs同步器  纯java实现的
     *
     * 下面我们手写一个aqs同步器  保证当前线程执行该代码块时不被打断
     *
     */
    /**
     * 减库存
     * @return
     */
    public String createOrder() {

        sysnc.lock();
        Integer stock;
        List<Map<String, Object> > query = saleTicketMapper.query();
        if (query == null || query.isEmpty() || (stock = (Integer) query.get(0).get("stock"))<=0){
            log.info("下单失败，已售罄");
            sysnc.unlock();
            return "下单失败，已售罄";
        }
        stock--;
        saleTicketMapper.update( stock);
        log.info("下单成功，当前剩余数量：----》{}",stock);
        sysnc.unlock();
        return "下单成功当前剩余数量：----》"+stock;
    }
}
